package com.yh.musicplayer.data;

/**
 * Created by yxf on 2018/10/31.
 */


import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yh.musicplayer.MainActivity;
import com.yh.musicplayer.R;

import net.qiujuer.genius.blur.StackBlur;

import java.util.Timer;
import java.util.TimerTask;

import static android.R.attr.radius;
import static android.R.attr.saveEnabled;

public class disc extends MainActivity implements GestureDetector.OnGestureListener{
    private ObjectAnimator discObjectAnimator,neddleObjectAnimator;
    private GestureDetector gestureDetector;
    //播放模式常量
    private static final int MODE_RANDOM_PLAY=0;
    private static final int MODE_SINGLE_CYCLE=1;
    private static final int MODE_LIST_CYCLE=2;

    //退出判断
    private static boolean isExit=false;

    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ImageButton img_playmode;
    private int playmode;
    private int status;
    private TextView textView;
    private RelativeLayout root_Layout;
    //广播接收器
    private StatusChangedReceiver receiver;
    private TextView text_Current;
    private TextView text_Duration;
    private SeekBar seekBar;
    private Handler seekBarHandler;
    //当前歌曲持续时间和位置，进度条
    private int duration;
    private int time;
    //进度条控制常量
    private static final int PROGRESS_INCREASE=0;
    private static final int PROGRESS_PAUSE=1;
    private static final int PROGRESS_RESET=2;

    private int number=0;

    private RelativeLayout relativeLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.disc);
        gestureDetector = new GestureDetector(this,this);

        //唱片绘制
        disc_show();

        //绑定广播接收器
        bindStatusChangedReceiver();
        startService(new Intent(this, MusicService.class));
        status=MusicService.COMMAND_STOP;

        //要删，默认播放模式是顺序
        playmode=disc.MODE_LIST_CYCLE;
        initSeekBarHandler();
        duration=0;
        time=0;
        findViews();
        registerListeners();
        which_activity=0;

    }

    //唱片动画实现
    private void disc_show(){
        //最外部的半透明边线
        OvalShape ovalShape0 = new OvalShape();
        ShapeDrawable drawable0 = new ShapeDrawable(ovalShape0);
        drawable0.getPaint().setColor(0x10000000);
        drawable0.getPaint().setStyle(Paint.Style.FILL);
        drawable0.getPaint().setAntiAlias(true);

        //黑色唱片边框
        RoundedBitmapDrawable drawable1 = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.disc));
        drawable1.setCircular(true);
        drawable1.setAntiAlias(true);

        //内层黑色边线
        OvalShape ovalShape2 = new OvalShape();
        ShapeDrawable drawable2 = new ShapeDrawable(ovalShape2);
        drawable2.getPaint().setColor(Color.BLACK);
        drawable2.getPaint().setStyle(Paint.Style.FILL);
        drawable2.getPaint().setAntiAlias(true);

        //最里面的图像
        RoundedBitmapDrawable drawable3 = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.disc_bg));
        drawable3.setCircular(true);
        drawable3.setAntiAlias(true);

        Drawable[] layers = new Drawable[4];
        layers[0] = drawable0;
        layers[1] = drawable1;
        layers[2] = drawable2;
        layers[3] = drawable3;


        LayerDrawable layerDrawable = new LayerDrawable(layers);

        int width = 10;
        //针对每一个图层进行填充，使得各个圆环之间相互有间隔，否则就重合成一个了。
        //layerDrawable.setLayerInset(0, width, width, width, width);
        layerDrawable.setLayerInset(1, width , width, width, width );
        layerDrawable.setLayerInset(2, width * 11, width * 11, width * 11, width * 11);
        layerDrawable.setLayerInset(3, width * 12, width * 12, width * 12, width * 12);

        final View discView = findViewById(R.id.myView);
        discView.setBackgroundDrawable(layerDrawable);

        ImageView needleImage= (ImageView) findViewById(R.id.needle);

        discObjectAnimator = ObjectAnimator.ofFloat(discView, "rotation", 0, 360);
        discObjectAnimator.setDuration(20000);
        //使ObjectAnimator动画匀速平滑旋转
        discObjectAnimator.setInterpolator(new LinearInterpolator());
        //无限循环旋转
        discObjectAnimator.setRepeatCount(ValueAnimator.INFINITE);
        discObjectAnimator.setRepeatMode(ValueAnimator.RESTART);


        neddleObjectAnimator = ObjectAnimator.ofFloat(needleImage, "rotation", 0, 25);
        needleImage.setPivotX(0);
        needleImage.setPivotY(0);
        neddleObjectAnimator.setDuration(800);
        neddleObjectAnimator.setInterpolator(new LinearInterpolator());
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
    }

    private void bindStatusChangedReceiver(){
        receiver=new StatusChangedReceiver();
        IntentFilter filter=new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver,filter);
    }

    private void findViews(){
        imgBtn_Previous=(ImageButton) findViewById(R.id.disc_previous);
        imgBtn_PlayOrPause=(ImageButton) findViewById(R.id.disc_play);
        // imgBtn_Stop=(ImageButton) findViewById(R.id.imageButton3);
        img_playmode=(ImageButton)findViewById(R.id.disc_playmode);
        imgBtn_Next=(ImageButton) findViewById(R.id.disc_next);
        root_Layout = (RelativeLayout) findViewById(R.id.disc_relativeLayout);
        textView=(TextView)findViewById(R.id.disc_textView);
        seekBar=(SeekBar)findViewById(R.id.disc_seekBar);
        text_Current=(TextView)findViewById(R.id.disc_textView1);
        text_Duration=(TextView)findViewById(R.id.disc_textView2);
        relativeLayout=(RelativeLayout)findViewById(R.id.relativeLayout_disc);
    }

    private void registerListeners(){
        img_playmode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (playmode){
                    case 0:
                        img_playmode.setBackgroundResource(R.drawable.list_recycle);
                        playmode=disc.MODE_LIST_CYCLE;
                        Toast.makeText(getApplicationContext(),"列表循环",Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        img_playmode.setBackgroundResource(R.drawable.random_play);
                        playmode=disc.MODE_RANDOM_PLAY;
                        Toast.makeText(getApplicationContext(),"随机播放",Toast.LENGTH_SHORT).show();

                        break;
                    case 2:
                        img_playmode.setBackgroundResource(R.drawable.single_recycle);
                        playmode=disc.MODE_SINGLE_CYCLE;
                        Toast.makeText(getApplicationContext(),"单曲循环",Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                sendBroadcastOnCommand(MusicService.COMMAND_PLAYMODE_CHANGED);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(status!=MusicService.STATUS_STOPPED){
                    time=seekBar.getProgress();
                    text_Current.setText(formatTime(time));
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if(status==MusicService.STATUS_PLAYING){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }if(status==MusicService.STATUS_PAUSED){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
            }
        });
        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (playmode){
                    case disc.MODE_RANDOM_PLAY:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                        break;
                    case disc.MODE_SINGLE_CYCLE:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
                        break;
                }

            }
        });

        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status){
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.STATUS_STOPPED:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                }
            }
        });

        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (playmode){
                    case disc.MODE_RANDOM_PLAY:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                        break;
                    case disc.MODE_SINGLE_CYCLE:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        break;
                }
            }
        });

    }

    //实现启动服务，检查播放状态
    protected void onResume(){
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        which_activity=0;
    }

    private void sendBroadcastOnCommand(int command){
        Intent intent=new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command",command);
        switch (command){
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number",number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time",time);
                break;
            case MusicService.COMMAND_PLAYMODE_CHANGED:
                intent.putExtra("playmode",playmode);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    private String formatTime(int msec){
        int minute=msec/1000/60;
        int second=msec/1000%60;
        String minuteString;
        String secondString;
        if(minute<10)
            minuteString="0"+minute;
        else
            minuteString=""+minute;
        if (second<10)
            secondString="0"+second;
        else
            secondString=""+second;
        return minuteString+":"+secondString;
    }

    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }
    //更新播放模式的图标
    private void updateplaymode_src(int playmode1){
        switch (playmode1){
            case 0:
                img_playmode.setBackgroundResource(R.drawable.random_play);
                break;
            case 1:
                img_playmode.setBackgroundResource(R.drawable.single_recycle);
                break;
            case 2:
                img_playmode.setBackgroundResource(R.drawable.list_recycle);
                break;
            default:
                break;
        }
    }

    //内部类，用来更新播放器状态
    class StatusChangedReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent){
            String musicName=intent.getStringExtra("musicName");
            String musicArtist=intent.getStringExtra("musicArtist");
            //获取播放器状态
            status=intent.getIntExtra("status",-1);
            switch (status){
                case MusicService.STATUS_PLAYING:
                    playmode=intent.getIntExtra("playmode",playmode);
                    updateplaymode_src(playmode);

                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time=intent.getIntExtra("time",0);
                    duration=intent.getIntExtra("duration",0);
                    number=intent.getIntExtra("number",number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                    text_Duration.setText(formatTime(duration));
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                    disc.this.setTitle("正在播放:"+musicName+"-"+musicArtist);
                    disc.this.textView.setText(musicName+"-"+musicArtist);

                    discObjectAnimator.start();
                    neddleObjectAnimator.start();
                    break;
                case MusicService.STATUS_PAUSED:
                    playmode=intent.getIntExtra("playmode",playmode);
                    updateplaymode_src(playmode);

                    time=intent.getIntExtra("time",0);
                    duration=intent.getIntExtra("duration",0);
                    number=intent.getIntExtra("number",number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    disc.this.textView.setText(musicName+"-"+musicArtist);
                    text_Duration.setText(formatTime(duration));
                    text_Current.setText(formatTime(time));
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                    discObjectAnimator.pause();
                    neddleObjectAnimator.reverse();
                    break;
                case MusicService.STATUS_STOPPED:
                    time=0;
                    duration=0;
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                    disc.this.setTitle("");
                    discObjectAnimator.cancel();
                    neddleObjectAnimator.reverse();
                    break;
                case MusicService.STATUS_COMPLETED:
                    number=intent.getIntExtra("number",0);
                    if(playmode==disc.MODE_RANDOM_PLAY)
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                    else if(playmode==disc.MODE_SINGLE_CYCLE)
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    else if(playmode==disc.MODE_LIST_CYCLE){
                        if(number==MusicList.getMusicList().size()-1){
                            number=0;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        }
                        else
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    }
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    disc.this.setTitle("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    discObjectAnimator.cancel();
                    neddleObjectAnimator.reverse();
                    break;
                default:
                    break;
            }
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (which_activity == 0){
                    Intent intent=new Intent();
                    intent.setClass(disc.this,MainActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.fragment_slide_up,R.anim.fragment_slide_down);
                    finish();
                }
                break;
        }
        return false;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent arg0,MotionEvent arg1,float arg2,float arg3) {
        if(arg1.getX()-arg0.getX()>150){
            Intent intent=new Intent();
            intent.setClass(disc.this,MainActivity.class);
            startActivity(intent);
            finish();
            overridePendingTransition(R.anim.to_right_enter,R.anim.to_right_exit);
        }
        return false;
    }
    //重写onToughEvent
    public boolean onToughEvent(MotionEvent event){
        return gestureDetector.onTouchEvent(event);
    }
    public boolean dispatchTouchEvent(MotionEvent event){
        if(gestureDetector.onTouchEvent(event)){
            event.setAction(MotionEvent.ACTION_CANCEL);
        }
        return super.dispatchTouchEvent(event);
    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (status == MusicService.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        discObjectAnimator.cancel();
        neddleObjectAnimator.reverse();
        super.onDestroy();
    }
}
